package com.syg.Commons.Test;

import com.alibaba.fastjson.JSONObject;
import com.syg.springboot05.properValue._02_ProperValues;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

@Controller
public class Test01 {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private _02_ProperValues properValues;

    @RequestMapping("ConfigurationProperties")
    @ResponseBody
    public String test1() {
        System.out.println(properValues.getFilePath() + "\n" + properValues.getUserName() + "\n" + properValues.getPassword());
        return properValues.getFilePath() + "\n" + properValues.getUserName() + "\n" + properValues.getPassword();
    }

    /**
     * 2,测试logger对象打印Json
     */
    @RequestMapping("/PrintJson")
    public void test2() {
        JSONObject reqJson = new JSONObject();
        reqJson.put("name", "shenyiguang");
        reqJson.put("age", 18);
        logger.info("我就看json的打印日志===>" + reqJson);
        System.out.println(reqJson);
    }

    /**
     * 3,测试JSON中包含null的情况
     * 特别注意@ResponseBody的用法
     *
     * @return
     */
    @RequestMapping("/jsonnull")
    @ResponseBody
    public String test3() {
        JSONObject reqJson = new JSONObject();
        reqJson.put("name", null);
        reqJson.put("age", 18);
        return "你好";
    }

    /**
     * 4,校验request.getInputStream()、request.getReader、request.getParameter()等方法
     *
     * @return
     */
    @RequestMapping("/getParameter")
    @ResponseBody
    public String test4(HttpServletRequest request) throws IOException {
        //String key = request.getParameter("key");//获取数据中的单个value
        //String queryString = request.getQueryString();//get方式获取所有的内容
        BufferedReader reader = request.getReader();
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    /**
     * 5,根据request对象获取ip地址
     *
     * @param request
     * @return
     */
    @RequestMapping("getIp")
    @ResponseBody
    public String test5(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        String currentIp = request.getRemoteAddr();
        logger.info("当前客户的IP===>" + ip + currentIp);
        return ip + currentIp;
    }

}
